﻿using System;
using System.Management.Automation;
using System.Runtime.InteropServices;
using Microsoft.SharePoint.PowerShell;

namespace CodeCounsel.SharePoint2010.DigiD.Cmdlets
{
    [SPCmdlet(RequireLocalFarmExist = true, RequireUserFarmAdmin = true)]
    [Cmdlet(VerbsCommon.Set, "DigiDSettings")]
    public class SetDigiDSettingsCmdlet : SPSetCmdletBase<DigiDSettings>
    {
        [Parameter(Mandatory = true, Position = 0, ValueFromPipeline=true)]
        public DigiDSettingsPipeBind Identity { get; set; }

        [Parameter(Mandatory = false, Position = 1)]
        public Uri ServerUrl { get; set; }

        [Parameter(Mandatory = false, Position = 2)]
        public string ServerID { get; set; }

        [Parameter(Mandatory = false, Position = 3)]
        public string ApplicationID { get; set; }

        [Parameter(Mandatory = false, Position = 4)]
        public SecurityLevel SecurityLevel { get; set; }

        [Parameter(Mandatory = false, Position = 5)]
        public string SharedSecret { get; set; }

        [Parameter(Mandatory = false, Position = 6)]
        public Uri SiteUrl { get; set; }

        protected override void InternalValidate()
        {
            DataObject = Identity.Read();
            base.InternalValidate();
        }

        protected override void UpdateDataObject()
        {           
            if (ServerUrl != null)
            {
                DataObject.ServerUrl = ServerUrl;
            }
            if (SiteUrl != null)
            {
                DataObject.SiteUrl = SiteUrl;
            }
            if (!String.IsNullOrEmpty(ServerID))
            {
                DataObject.ServerID = ServerID;
            }
            if (!String.IsNullOrEmpty(ApplicationID))
            {
                DataObject.ApplicationID = ApplicationID;
            }
            if (SecurityLevel != SecurityLevel.NotSet)
            {
                DataObject.SecurityLevel = SecurityLevel;
            }
            if (!String.IsNullOrEmpty(SharedSecret))
            {
                DataObject.SharedSecret = SharedSecret;
            }
            DataObject.Update();
        }
    }
}
